package com.wave.wavesystem.serve.init;

import com.wave.common.model.KV;
import com.wave.common.util.Func;
import com.wave.wavesystem.serve.enums.user.UserRoleEnum;
import com.wave.wavesystem.serve.pojo.entity.UserRole;
import com.wave.wavesystem.serve.service.IUserRoleService;
import jakarta.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class UserRoleInit implements CommandLineRunner {

    @Resource
    private IUserRoleService userRoleService;

    @Override
    public void run(String... args) throws Exception {

        List<UserRole> list = userRoleService.list();
        List<KV<String, String>> intiRoles = UserRoleEnum.list();
        // 没有数据 插入系统必备角色
        if (list.isEmpty()) {
            List<UserRole> roles = intiRoles.stream().map(item -> {
                UserRole userRole = new UserRole();
                userRole.setEnName(item.getValue());
                userRole.setName(item.getKey());
                return userRole;
            }).toList();
            userRoleService.saveBatch(roles);
            return;
        }
        Set<String> collect = list.stream().map(UserRole::getEnName)
                .collect(Collectors.toSet());

        List<UserRole> requireInsert = intiRoles.stream().filter(item -> !collect.contains(item.getValue()))
                .map(item -> {
                    UserRole userRole = new UserRole();
                    userRole.setEnName(item.getValue());
                    userRole.setName(item.getKey());
                    return userRole;
                }).toList();

        if (Func.isNotEmpty(requireInsert)) {
            userRoleService.saveBatch(requireInsert);
        }

    }

}
